/**
 * @file editor
 * @author liaoxuezhi@baidu.com
 */
/* eslint-disable */

import * as React from 'react';
import {
  Component,
  PropTypes
} from 'react';
import FroalaEditor from './lib/froalaEditor';
import '../rich-text.scss';
import * as cx from 'classnames';
import * as assign from 'object-assign';
import {ubb2html, html2ubb} from './ubb';

const config = {
  // charCounterCount: false,
  language: 'zh_cn',
  toolbarButtonsSM: [
    'paragraphFormat', 'quote', 'color', '|', 'bold', 'italic', 'underline', 'strikeThrough', '|',  'formatOL', 'formatUL', 'align', '|', 'insertLink', 'insertImage', 'insertEmotion', 'insertTable', '|', 'undo', 'redo', 'html'
  ],
  toolbarButtonsMD: [
    'paragraphFormat', 'quote', 'color', '|', 'bold', 'italic', 'underline', 'strikeThrough', '|',  'formatOL', 'formatUL', 'align', '|', 'insertLink', 'insertImage', 'insertEmotion', 'insertTable', '|', 'undo', 'redo', 'html'
  ],
  toolbarButtons: [
    'paragraphFormat', 'quote', 'color', '|', 'bold', 'italic', 'underline', 'strikeThrough', '|',  'formatOL', 'formatUL', 'align', '|', 'insertLink', 'insertImage', 'insertEmotion', 'insertTable', '|', 'undo', 'redo', 'html'
  ]
};

export default class FroalaEditorWrapper extends Component {
  static propTypes = {
    className: PropTypes.string
  };

  value = null;
  constructor(props) {
    super(props);

    this.handleFocus = this.handleFocus.bind(this);
    this.handleBlur = this.handleBlur.bind(this);
    this.handleChange = this.handleChange.bind(this);

    const buttons = {};

    if (props.buttons) {
      buttons.toolbarButtonsSM = props.buttons;
      buttons.toolbarButtonsMD = props.buttons;
      buttons.toolbarButtonsXS = props.buttons;
      buttons.toolbarButtons = props.buttons;
    }

    const info = this.parseInput(props);
    this.value = info.value;
    this.state = {
      focused: false,
      model: info.html,
      config: assign({
        imageAllowedTypes: ['jpeg', 'jpg', 'png', 'gif'],
        imageDefaultAlign: 'left',
        imageEditButtons: props.imageEditable ? ["imageReplace", "imageAlign", "imageRemove", "|", "imageLink", "linkOpen", "linkEdit", "linkRemove", "-", "imageDisplay", "imageStyle", "imageAlt", "imageSize"] : [],
      }, props.options, config, {
        editorClass: props.editorClass,
        placeholderText: props.placeholder,
        imageUploadURL: props.reciever,
        events: {
          'froalaEditor.focus': this.handleFocus,
          'froalaEditor.blur': this.handleBlur
        }
      }, buttons)
    };
  }

  componentDidMount() {
    this.mayTriggerChange();
  }

  componentWillReceiveProps(nextProps) {
    const props = this.props;

    if (props.value !== nextProps.value && nextProps.value !== this.value) {
      const info = this.parseInput(nextProps);
      this.value = info.value;
      this.setState({
        model: info.html,
      });
    }
  }

  componentDidUpdate() {
    this.mayTriggerChange();
  }

  mayTriggerChange() {
    if (this.needTriggerChange) {
      const info = this.needTriggerChange;
      this.needTriggerChange = null;
      this.handleChange(info.html, info.value, true);
    }
  }

  parseInput(props) {
    let value = props.value;
    let html = value;

    if (props.saveAsUbb && value) {
      if (/<\/?\w+\s*[^>]*>/.test(value)) {
        html = value;
        value = html2ubb(html);

        // 标记输入是 html, 下次更新到 dom 后，触发 change.
        this.needTriggerChange = {html, value};
      } else {
        html = ubb2html(value);
      }
    }
    return {
      value,
      html
    }
  }

  handleFocus() {
    this.setState({
      focused: true
    });
  }

  handleBlur() {
    this.setState({
      focused: false
    });
  }

  handleChange(value, ubb = null, force = false) {
    const {
      onChange,
      saveAsUbb
    } = this.props;

    const model = value;
    if (saveAsUbb) {
      value = ubb || html2ubb(value);
    }

    if (this.value === value && !force) {
      return;
    }
    this.value = value;
    this.setState({
      model: model
    }, () => onChange && onChange(value));
  }

  render() {
    const {
      className,
      maxLength,
      value,
      size,
      disabled,
    } = this.props;
    let config = {
        ...this.state.config
    };
    // 不可编辑
    if(disabled) {
      // console.info("as");
      config.events = {
        'froalaEditor.focus' : function(e, editor) {
            // console.log("sda");
            editor.edit.off();
        }
      };
    }
    return (
      <div
        className={cx('rich-text-editor', className, size ? `rich-text-editor-${size}` : null, {
          'focus': this.state.focused,
          'with-statistics': maxLength
        })}
      >
        <FroalaEditor
          tag='textarea'
          config={config}
          model={this.state.model}
          onModelChange={this.handleChange}
          onFocus={this.handleFocus}
          onBlur={this.handleBlur}
        />

        {maxLength ? (
            <span className="text-count">
              {`还可以输入${Math.max(maxLength - (value && value.length || 0), 0)}个字`}
            </span>
          ) : null}
      </div>
    );
  }
}

export {
  ubb2html,
  html2ubb
}